﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Casamiel.API.Application;
using Casamiel.API.Application.Commands;
using Casamiel.API.Application.Models;
using Casamiel.API.Application.Models.ICModels;
using Casamiel.API.Application.Models.Store;
using Casamiel.API.Application.Models.V2;
using Casamiel.API.Application.Services;
using Casamiel.API.Infrastructure;
using Casamiel.API.Infrastructure.Exceptions;
using Casamiel.API.Infrastructure.Filters;
using Casamiel.Application;
using Casamiel.Application.Commands;
using Casamiel.Application.Commands.Order;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain;
using Casamiel.Domain.Entity;
using Casamiel.Domain.Request;
using Casamiel.Domain.Request.IC;
using Casamiel.Domain.Response;
using Enyim.Caching;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.API.Controllers.V2
{
    /// <summary>
    /// 
    /// </summary>
    [Produces("application/json")]
    [ApiVersion("2.0")]
    [Route("api/v{api-version:apiVersion}/Order")]
    [TypeFilterAttribute(typeof(CheckTokenAttribute))]
    [Authorize]
    [ApiController]
    public class OrderController : BaseController
    {
        private readonly NLog.ILogger logger = NLog.LogManager.GetLogger("OrderService");
        private readonly IIcApiService _icApiService;

        private readonly CasamielSettings _settings;
        private readonly IMemberCardService _memberCardService;
        private readonly IUserLogService _userLog;
        private readonly IStoreApiService _storeApiService;
        private readonly IStoreService _storeService;
        private readonly ICasaMielSession _session;
        private readonly IPaymentService _paymentService;
        private readonly IRefundService _refundService;
        private readonly IMediator _mediator;
        private readonly string _memcachedPrex;
        private readonly IMemcachedClient _memcachedClient;
        private readonly INoticeService _notice;
        private readonly IOrderService _order;
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Casamiel.API.Controllers.V2.OrderController"/> class.
        /// </summary>
        /// <param name="notice"></param>
        /// <param name="settings">Settings.</param>
        /// <param name="memberCard">Member card.</param>
        /// <param name="iicApiService">Iic API service.</param>
        /// <param name="memcachedClient"></param>
        /// <param name="userLog">User log.</param>
        /// <param name="storeApiService">Store API service.</param>
        /// <param name="storeService">Store service.</param>
        /// <param name="session">Session.</param>
        /// <param name="paymentService">Payment service.</param>
        /// <param name="refundService">refund Service</param>
        /// <param name="mediator"></param>
        /// <param name="order"></param>
        public OrderController(INoticeService notice, IOptionsSnapshot<CasamielSettings> settings,
           IMemberCardService memberCard,
            IIcApiService iicApiService, IMemcachedClient memcachedClient,
            IUserLogService userLog, IStoreApiService storeApiService,
                              IStoreService storeService, ICasaMielSession session, IPaymentService paymentService,
                              IRefundService refundService
                               , IMediator mediator, IOrderService order)
        {
            if (settings == null) {
                throw new ArgumentNullException(nameof(settings));
            }

            _notice = notice;
            _settings = settings.Value;
            _icApiService = iicApiService;

            _userLog = userLog;
            _storeApiService = storeApiService;
            _storeService = storeService;
            _memberCardService = memberCard;
            _session = session;
            _paymentService = paymentService;
            _refundService = refundService;
            _mediator = mediator;
            _memcachedPrex = settings.Value.MemcachedPre;
            _memcachedClient = memcachedClient;
            _order = order;
        }

        /// <summary>
        /// 我的的订单
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <remarks>{"pageindex":1,"pagesize":10,"orderStatus":0}</remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> MyOrders([FromBody]JObject data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var pageindex = data["pageindex"].ToInt32(1);
            var pagesize = data["pagesize"].ToInt32(10);
            var mobile = MemberHelper.GetMobile(token);
            Random a = new Random();
            var aaa = a.NextDouble();
            if (aaa < 0.5) {
                System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
                watch.Start();
                var result = await _storeApiService.GetMYOrderList(mobile, data["pageindex"].ToInt32(1), data["pagesize"].ToInt32(10), data["orderStatus"].ToInt32(99)).ConfigureAwait(false);
                var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
                var entity = JsonConvert.DeserializeObject<List<OrderBaseRsp>>(dynamicdata["Data"].ToString());
                //var pageindex = dynamicdata["PageIndex"].ToInt32(1);
                //var pagesize = dynamicdata["PageSize"].ToInt32(10);
                var total = dynamicdata["Total"].ToInt32(0);
                watch.Stop();
                logger.Trace($"GetMYOrderList:执行时间：{watch.ElapsedMilliseconds}毫秒");
                return Ok(new { code = 0, pageindex, pagesize, total, content = entity });
            } else {
                var total = 0;
                System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
                watch.Start();
                var list = new List<OrderBaseRsp>();
                _storeApiService.GetMyOrderList(mobile, data["pageindex"].ToInt32(1), data["pagesize"].ToInt32(10), data["orderStatus"].ToInt32(99), ref list, ref total);

                watch.Stop();
                logger.Trace($"GetMYOrderList-ref:执行时间：{watch.ElapsedMilliseconds}毫秒");
                return Ok(new { code = 0, pageindex, pagesize, total, content = list });
            }
        }
        /// <summary>
        /// Mies the orders by app.
        /// </summary>
        /// <returns>The orders by app.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<PagingResultRsp<List<CakeOrderGetListRsp>>> MyOrdersByAPP([FromBody]GetMyAllOrdersReq req, [FromHeader(Name = "u-token")] string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }

            var mobile = MemberHelper.GetMobile(token);
            var command = new GetAllOrderListCommand(req.PageIndex, req.PageSize, req.Status, mobile);
            var result = await _mediator.Send(command).ConfigureAwait(false);
            return result;
        }

        /// <summary>
        /// 取消订单(完善中）
        /// </summary>
        /// <returns>The orders.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        /// <remarks>
        /// {"orderCode":"XXXXXX"}
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> CancleOrders([FromBody]JObject data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            var entity = await _order.GetByOrderCodeAsync<ICasaMielSession>(data["orderCode"].ToString(), mobile).ConfigureAwait(false);
            if (entity != null) {
                if (entity.OrderStatus == (int)OrderStatus.Paid) {

                    //var cmd = new CancelMemberCouponCommand("", data["orderCode"].ToString(), 1, 6);
                    //var rsp = await _mediator.Send(cmd).ConfigureAwait(false);
                    //if (rsp.Code != 0) {
                    //    return Ok(rsp);
                    //}
                    //tuikuan
                    var payinfo = await _paymentService.FindAsync<ICasaMielSession>(entity.OrderCode, (int)OperationMethod.CakeStore, 1).ConfigureAwait(false);
                    if (payinfo.PayMethod == 3) {
                        var re = await _icApiService.Icconsumeback(new IcConsumeBackReq { Tradeno = payinfo.IcTradeNO, Phoneno = payinfo.Mobile }).ConfigureAwait(false);
                        if (re.code == 0 || re.code == 205) {
                            if (re.code == 0) {
                                JObject obj = JsonConvert.DeserializeObject<JObject>(re.content);
                                logger.Trace($"OrderCode:{entity.OrderCode},tradeno_origin:{obj["tradeno_origin"].ToString()},tradeno:{obj["tradeno"].ToString()},");
                                var billno = obj["tradeno"].ToString();
                                using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                                    entity.CloseTime = DateTime.Now;
                                    entity.OrderStatus = (int)OrderStatus.Cancelled;
                                    var s = await _order.OrderBaseUPdateAsync(entity, uow).ConfigureAwait(true);
                                    var take = await _order.UpdateOrderTakeStatus(entity.OrderBaseId, -1, billno, uow).ConfigureAwait(true);
                                    var dis = await _order.UpdateOrderDiscountStatus(entity.OrderBaseId, 1, uow).ConfigureAwait(true);
                                    var noticEntity = new NoticeBaseEntity() {
                                        RemindTime = DateTime.Now.AddMinutes(-1),
                                        CreateTime = DateTime.Now,
                                        RelationId = entity.OrderBaseId,
                                        StoreId = entity.StoreId,
                                        NoticeType = 3
                                    };
                                    await _notice.UpdateNoticeByRelationIdAsync(entity.OrderBaseId, 1, uow).ConfigureAwait(true);
                                    await _notice.AddAsync(noticEntity, uow).ConfigureAwait(true);
                                }
                            }
                        } else {
                            return Ok(re);
                        }
                    }
                } else if (entity.OrderStatus == (int)OrderStatus.Create) {
                    var dto = new IcConsumeBackReq { Phoneno = mobile, Tradeno = entity.IcTradeNO };
                    var d = await _icApiService.Icconsumeback(dto).ConfigureAwait(false);

                    if (d.code == 0 || d.code == 205) {
                        if (d.code == 0) {
                            JObject obj = JsonConvert.DeserializeObject<JObject>(d.content);
                            var billno = obj["tradeno"].ToString();
                            using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                                entity.CloseTime = DateTime.Now;
                                entity.OrderStatus = (int)OrderStatus.Cancelled;
                                var s = await _order.OrderBaseUPdateAsync(entity, uow).ConfigureAwait(true);
                                var take = await _order.UpdateOrderTakeStatus(entity.OrderBaseId, -1, billno, uow).ConfigureAwait(true);
                                var dis = await _order.UpdateOrderDiscountStatus(entity.OrderBaseId, 1, uow).ConfigureAwait(true);
                            }
                        }
                    }
                }
            }

            //var model = await _orders.GetMyOrders(1, 4, 1);
            return Ok(new { code = 0, content = entity });
        }
        /// <summary>
        /// Refund the specified data and token.
        /// </summary>
        /// <returns>The refund.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Refund([FromBody] OrderRefundReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);

            try {
                logger.Trace($"{JsonConvert.SerializeObject(data)}");

                var entity = await _order.GetByOrderCodeAsync<ICasaMielSession>(data.OrderCode, mobile).ConfigureAwait(false);
                logger.Trace($"Refund:{JsonConvert.SerializeObject(entity)}");
                if (entity != null) {
                    if (entity.OrderStatus == (int)OrderStatus.Paid)
                        {
                        if (entity.PayTime.Value.AddMinutes(10) < DateTime.Now) {
                            return Ok(new { code = 9999, msg = "超出订单取消时间，请联系门店" });
                        }
                        if (entity.ExpressStatus > 1) {
                            return Ok(new { code = 9999, msg = "已发货不能取消订单" });
                        }

                        var cmd = new CancelMemberCouponCommand("", data.OrderCode, 1, 6);
                        var rsp = await _mediator.Send(cmd).ConfigureAwait(false);
                        if (rsp.Code != 0) {
                            return Ok(rsp);
                        }
                        var m = await _refundService.OrderRefund(data).ConfigureAwait(false);
                        if (m.code == 0) {
                            var command = new CancelOrderMemberCouponCommand { OrderCode = data.OrderCode };
                            await _mediator.Publish(command).ConfigureAwait(false);
                            await _order.OrderOperationLogAddAsync<ICasaMielSession>(new OrderOperationLog {
                                BillType = 2, CreateTime = DateTime.Now, Remark = "用户发起订单取消成功",
                                OrderBaseId = entity.OrderBaseId, OrderCode = entity.OrderCode
                            }).ConfigureAwait(false);
                        }
                        return Ok(m);
                    } else {
                        return Ok(new { code = 9999, msg = "订单状态不是已支付" });
                    }
                } else {
                    return Ok(new { code = 9999, msg = "订单不存在！" });

                }
            } catch {
                throw;
            }

        }
        /// <summary>
        /// 我的优惠券
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetMyCoupon([FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            //todo：
            var cardinfo = await _memberCardService.GetBindCardAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            if (cardinfo != null) {
                var t = new GetTicticketReq { Cardno = cardinfo.CardNO, State = 2, Pageindex = 1, Pagesize = int.MaxValue };
                var a = await _icApiService.Geticticket(t).ConfigureAwait(false);
                if (a.code == 0) {
                    var list = JsonConvert.DeserializeObject<TicketItemRoot>(a.content);
                    return Ok(new { code = 0, content = list.Tickets });
                }
            }
            var tickent = new List<TicketItem>();
            return Ok(new { code = 0, content = tickent });

        }
        /// <summary>
        /// 订单详情
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <remarks>
        /// {"orderCode":"XXXX"}
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetDetail([FromBody] JObject data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            var command = new GetCakeOrderDetailV2Command(mobile, data["orderCode"].ToString());
            var model = await _mediator.Send(command).ConfigureAwait(false);
            return Ok(model);
        }
        /// <summary>
        /// Payment the specified data and token.
        /// </summary>
        /// <returns>The payment.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Payment([FromBody] OrderPaymentReq data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            var order = await _order.GetByOrderCodeAsync<ICasaMielSession>(data.OrderCode, mobile).ConfigureAwait(false);
            if (order == null) {
                return Ok(new { code = -23, msg = "订单不存在" });
            }
            if (order.OrderStatus != (int)OrderStatus.Create) {
                return Ok(new { code = -24, msg = "订单状态不是待支付" });
            }
            if (order.OrderType == 1) {
                var orderTake = await _storeService.GetOrdeTakeByOrderCodeAsync<ICasaMielSession>(order.OrderBaseId).ConfigureAwait(false);
                if (orderTake == null) {
                    return Ok(new { code = -26, msg = "提货单据出错" });
                }
                if (order.CreateTime.DayOfYear == orderTake.TakeTime.DayOfYear) {
                    if (order.CreateTime.DayOfYear == DateTime.Now.DayOfYear) {
                        if (orderTake.TakeTime <= DateTime.Now) {
                            return Ok(new { code = -24, msg = "订单状态不是待支付" });
                        }
                    }
                } else {
                    if (orderTake.TakeTime.DayOfYear == DateTime.Now.DayOfYear || orderTake.TakeTime.DayOfYear < DateTime.Now.DayOfYear) {
                        return Ok(new { code = -24, msg = "订单状态不是待支付" });
                    }
                }
            }

            if (data.DiscountCouponId > 0) {

                var a = await _icApiService.Geticticket(new GetTicticketReq { Cardno = data.CardNO, Pagesize = 200, State = 2, Pageindex = 1 }).ConfigureAwait(false);
                if (a.code == 0) {
                    var list = JsonConvert.DeserializeObject<TicketItemRoot>(a.content);
                    var ticket = list.Tickets.Where(t => t.Ticketid == data.DiscountCouponId).SingleOrDefault();
                    if (ticket != null) {
                        data.DiscountCouponMoney = ticket.Je.ToDecimal(0);
                    } else {
                        return Ok(new { code = -23, msg = "优惠券不可用" });
                    }
                } else {
                    return Ok(new { code = -23, msg = "优惠券不可用" });
                }
            }
            var p_tradeno = $"C{DateTime.Now.ToString("yyMMddHHmmssfff", CultureInfo.CurrentCulture)}";
            var reorder = await _storeApiService.GetOrderByOrderCodeAsync(data.OrderCode, mobile).ConfigureAwait(false);
            var payment = new PaymentRecord {
                OperationMethod = (int)OperationMethod.CakeStore,
                TradeNo = p_tradeno,
                Amount = order.PayCashMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                PayMethod = data.PayMethod,
                BillNO = order.OrderCode,
                IcTradeNO = order.IcTradeNO,
                State = 0,
                OperationState = 0,
                CreateTime = DateTime.Now,
                Mobile = mobile
            };
            var shopno = "";
            var shopinfo = await _paymentService.GetShopIdAndShopNameByBillNOAsync<ICasaMielSession>(order.OrderCode).ConfigureAwait(false);
            payment.ShopName = shopinfo.Item2;
            payment.ShopId = shopinfo.Item1;

            var cachekey = string.Format(CultureInfo.CurrentCulture, Constant.SHOPNO, _memcachedPrex, payment.ShopId.Value);
            shopno = await _memcachedClient.GetValueAsync<string>(cachekey).ConfigureAwait(false);
            if (string.IsNullOrEmpty(shopno)) {
                var basedata = await _icApiService.BasedataQuery(new BasedataqueryReq { Datatype = 3, Datavalue = $"{payment.ShopId.Value}" }).ConfigureAwait(false);
                if (basedata.code == 0) {
                    var d = JsonConvert.DeserializeObject<JArray>(basedata.content);
                    if (d.Count > 0) {
                        shopno = d[0]["no"].ToString();
                        await _memcachedClient.AddAsync(cachekey, shopno, 72000).ConfigureAwait(false);
                    }
                }
            }
            payment.ShopNO = shopno;


            if (order.PayCashMoney == 0) {
                var pay = new IcConsumepayReq {
                    Shopid = reorder.StoreRelationId,
                    Tradeno = reorder.IcTradeNo,
                    Phoneno = mobile
                };
                pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>();

                if (data.DiscountCouponId > 0) {
                    pay.Paycontent.Add(new IcConsumepayReq.PaycontentItem {
                        Paytype = "6",
                        Paymoney = data.DiscountCouponMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                        Paytradeno = $"t{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}",
                        Payuser = $"{data.DiscountCouponId}"
                    });
                }


                var zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);
                if (zmodel.code == 0) {
                    payment.PayMethod = data.PayMethod;
                    payment.PayTime = DateTime.Now;
                    payment.State = 1;
                    payment.OperationState = 1;
                    using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                        order.OrderStatus = (int)OrderStatus.Paid;
                        order.PayTime = DateTime.Now;
                        await _order.OrderBaseUPdateAsync(order, uow).ConfigureAwait(true);
                        await _order.UpdateOrderTakeStatus(order.OrderBaseId, 0, "", uow).ConfigureAwait(true);
                        payment.State = 1;
                        payment.OperationState = 1;
                        payment.PayTime = DateTime.Now;
                        await _paymentService.AddAsync(payment, uow).ConfigureAwait(true);
                        var noticEntity = new NoticeBaseEntity() {
                            RemindTime = DateTime.Now.AddMinutes(-3),
                            CreateTime = DateTime.Now,
                            RelationId = order.OrderBaseId,
                            StoreId = order.StoreId,
                            NoticeType = 0
                        };
                        await _notice.AddAsync(noticEntity, uow).ConfigureAwait(true);

                    }
                    return new JsonResult(new { code = 0, content = new { paymentrequest = "", ordercode = order.OrderCode, payMethod = payment.PayMethod.ToString(CultureInfo.CurrentCulture), payed = true } });

                    //return new JsonResult(new { code = 0, content = entity, payMethod = payment.PayMethod, payed = true });
                }
                return Ok(zmodel);
            }
            switch (data.PayMethod) {
                case 3:
                    if (string.IsNullOrEmpty(data.PayCardNO)) {
                        return Ok(new { code = 999, msg = "卡号不能为空" });
                    }
                    var cardinfo = await _memberCardService.FindAsync<ICasaMielSession>(data.PayCardNO, mobile).ConfigureAwait(false);
                    if (cardinfo == null) {
                        return Ok(new { code = 999, msg = "卡号有误" });
                    }

                    var pay = new IcConsumepayReq {
                        Cardno = data.PayCardNO,
                        Shopid = reorder.StoreRelationId,
                        Tradeno = reorder.IcTradeNo,
                        Createinvoice = true
                    };
                    pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>
                    {
                        new IcConsumepayReq.PaycontentItem
                        {
                            Paytype = "3",
                            Paymoney = order.PayCashMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                            Paytradeno = $"c{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}"
                        }
                    };
                    if (data.DiscountCouponId > 0) {

                        pay.Paycontent.Add(new IcConsumepayReq.PaycontentItem {
                            Paytype = "6",
                            Paymoney = data.DiscountCouponMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                            Paytradeno = $"t{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}",
                            Payuser = $"{data.DiscountCouponId}"
                        });
                    }
                    var zcard = await _icApiService.GetCardBalance(data.PayCardNO, $"{LoginInfo.Item3}099".ToInt32(0)).ConfigureAwait(false);
                    if (zcard.code == 0) {
                        var Obj = JsonConvert.DeserializeObject<JObject>(zcard.content);
                        var balance = Obj["totalmoney"].ToDecimal(0);
                        if (balance < order.PayCashMoney) {
                            if (cardinfo.CardType == "3")//幸福卡
                            {
                                return Ok(new { code = -40, msg = "卡内余额不足" });
                            }
                            return Ok(new { code = -39, msg = "卡内余额不足" });
                        }
                        if ((data.PayMethod == 3) && (cardinfo.CardType == "3")) {
                            return Ok(new { code = -41, msg = "优惠券不能与幸福卡同时使用" });
                        }
                    } else {
                        return Ok(zcard);
                    }
                    payment.PayMethod = data.PayMethod;
                    payment.State = 1;
                    payment.OperationState = 1;
                    payment.PayTime = DateTime.Now;
                    var zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);
                    if (zmodel.code == 0) {
                        var jobject = JsonConvert.DeserializeObject<JObject>(zmodel.content);
                        if (jobject != null && jobject["invoiceqrcode"] != null) {
                            var invoiceUrl = jobject["invoiceqrcode"].ToString();
                            await _order.UpdateOrderInvoiceUrlByOrderCodeAsync<ICasaMielSession>(payment.BillNO, invoiceUrl).ConfigureAwait(false);
                        } else {
                            logger.Error($"Invoideurl:{zmodel.content}");
                        }
                        //var jobject = JsonConvert.DeserializeObject<JObject>(zmodel.content);
                        //var tradeno = jobject["tradeno"].ToString();
                        //payment.OutTradeNo = tradeno;
                        //todo:zhifucg
                        using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                            order.OrderStatus = (int)OrderStatus.Paid;
                            order.PayMethod = payment.PayMethod;
                            await _order.OrderBaseUPdateAsync(order, uow).ConfigureAwait(true);
                            await _order.UpdateOrderTakeStatus(order.OrderBaseId, 0, "", uow).ConfigureAwait(true);
                            await _paymentService.AddAsync(payment, uow).ConfigureAwait(true);

                            var noticEntity = new NoticeBaseEntity() {
                                RemindTime = DateTime.Now.AddMinutes(3),
                                CreateTime = DateTime.Now,
                                RelationId = reorder.OrderBaseId,
                                StoreId = reorder.StoreId,
                                NoticeType = 0
                            };
                            await _notice.AddAsync(noticEntity, uow).ConfigureAwait(true);
                        }
                        var logdata = new UserLog { Url = Request.GetShortUri(), OPInfo = $"蛋糕订单支付,卡号:[{data.CardNO},支付金额{order.PayCashMoney}，订单号：{order.OrderCode}", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                          await _mediator.Publish(new UserLogNoticeCommand(logdata)).ConfigureAwait(false);
                          return new JsonResult(new { code = 0, content = new { paymentrequest = "", ordercode = order.OrderCode, payMethod = payment.PayMethod.ToString(CultureInfo.CurrentCulture), payed = true } });

 
                    } else {
                        return new JsonResult(zmodel);
                    }
                default:
                    var command = new CreatePaymentRequestCommand(payment, data.id, PaymentScenario.CakeStore);
                    var result = await _mediator.Send(command).ConfigureAwait(false);
                    return Ok(new { code = 0, content = result });
                            
            }
           
        }

        /// <summary>
        /// 立即购买
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <remarks>
        /// </remarks>
        /// 
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> BuyNow([FromBody]BuyNowReq data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            if (string.IsNullOrEmpty(token)) {
                logger.Trace("failer");
            }
            logger.Trace($"BuyNow:{JsonConvert.SerializeObject(data)}");
            
            var storeinfo = await _storeService.GetDetail<ICasaMielSession>(data.storeid).ConfigureAwait(false);
            if (storeinfo == null) {
                return Ok(new { code = 9999, msg = "门店信息有误！" });
            }
            if (storeinfo.IsCakeShopClose == 1) {
                return Ok(new { code = 9999, msg = "抱歉门店已闭店！" });
            }

            if (storeinfo.IsCakeClose == 1) {
                return Ok(new { code = 9999, msg = "抱歉门店未营业！" });
            }
            if (data.picktime < DateTime.Now) {
                return Ok(new { code = -25, msg = "提货时间有误" });
            }


            var goodbase = await _storeApiService.GetGoodsBase(data.storeid, data.goodsBaseId).ConfigureAwait(false);
            logger.Trace($"{JsonConvert.SerializeObject(goodbase)}");
            if (goodbase == null || goodbase.Status == 1) {
                return Ok(new { code = -22, msg = "产品已经下架" });
            }

            goodbase.StoreName = storeinfo.StoreName;

            if (storeinfo.IsLimitStock == 0) {
                if (goodbase.StockDays > 1) {
                    if (data.picktime.DayOfYear != DateTime.Now.DayOfYear) {
                        if (data.picktime < DateTime.Parse(DateTime.Now.AddDays(goodbase.StockDays).ToString("yyyy-MM-dd 00:00:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)) {
                            return Ok(new { code = -28, msg = "本款蛋糕需提前2天预定" });
                        }
                    }
                }
            }
            goodbase.Quantity = data.count;
            goodbase.picktime = data.picktime;

            goodbase.storeRelationId = data.storeRelationId;
            var dto = new IcPriceReq { Shopid = data.storeRelationId, Product = new List<ProductItemReq>(),Datasource= $"{LoginInfo.Item3}099".ToInt32(0) };
            dto.Product.Add(new ProductItemReq { Pid = $"{data.relationId}", Count = data.count });
            var iczmodel = await _icApiService.Icprice(dto).ConfigureAwait(false);
            if (iczmodel != null && iczmodel.Product.Count > 0) {
                goodbase.Price = iczmodel.Product[0].Icprice;
            } else {
                logger.Error($"buynowerror:{JsonConvert.SerializeObject(dto)},{JsonConvert.SerializeObject(iczmodel)}");
                return Ok(new { code = -22, msg = "产品已经下架" });
            }
            if (DateTime.Parse(DateTime.Now.ToString("2018-05-20 20:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) < DateTime.Parse(data.picktime.ToString("2018-05-20 HH:mm:ss", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)) {
                return Ok(new { code = -23, msg = "抱歉该自提时间不能预定" });
            }
            if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)) {
                if (data.picktime < DateTime.Parse(DateTime.Now.AddDays(1).ToString("yyyyy-MM-dd 23:00:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)) {
                    var zmodel = await _icApiService.ProductStockQuery(dto).ConfigureAwait(false);
                    if (zmodel != null && zmodel.product.Count > 0) {
                        int a = await _storeService.GetGoodsQuantityByPidAsync<ICasaMielSession>(data.relationId, DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)).ConfigureAwait(false);

                        if (zmodel.product[0].count < (data.count + a)) {
                            return Ok(new { code = -21, msg = "库存不足" });
                        }
                    } else {
                        return Ok(new { code = -21, msg = "库存不足" });
                        //logger.Error($"buynowerror:{JsonConvert.SerializeObject(dto)},{JsonConvert.SerializeObject(zmodel)}");
                        //return Ok(new { code = -22, msg = "产品已经下架" });
                    }
                    return Ok(new { code = 0, content = goodbase, msg = "可以购买" });
                }

                return Ok(new { code = 0, content = goodbase, msg = "可以购买" });

            }




            if (data.picktime.DayOfYear == DateTime.Now.DayOfYear) {
                if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 20:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) && data.picktime.DayOfYear == DateTime.Now.DayOfYear) {
                    return Ok(new { code = -23, msg = "抱歉该时间段不能预定当天蛋糕自提" });
                }




                if (storeinfo.IsLimitStock == 0) {

                    var zmodel = await _icApiService.ProductStockQuery(dto).ConfigureAwait(false);
                    if (zmodel != null && zmodel.product.Count > 0) {

                        if (zmodel.product[0].count < data.count) {
                            return Ok(new { code = -21, msg = "库存不足" });
                        }
                    } else {
                        return Ok(new { code = -21, msg = "库存不足" });
                        //logger.Error($"buynowerror:{JsonConvert.SerializeObject(dto)},{JsonConvert.SerializeObject(zmodel)}");
                        //return Ok(new { code = -22, msg = "产品已经下架" });
                    }
                }
            }

            return Ok(new { code = 0, content = goodbase, msg = "可以购买" });
            //}
            //else
            //{
            //    return Ok(new { code = 0, content = goodbase, msg = "可以购买" });
            //}
        }
        /// <summary>
        /// 创建订单
        /// </summary>
        /// <returns>The order.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> CreateOrder([FromBody]CreateOrderReq data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            logger.Trace($"CreateOrder：{JsonConvert.SerializeObject(data)}");

            var storeinfo = await _storeService.GetDetail<ICasaMielSession>(data.storeid).ConfigureAwait(false);
            if (storeinfo == null) {
                return Ok(new { code = 9999, msg = "门店信息有误！" });
            }
            if (data.buyType == 1 && storeinfo.IsOpenSend == 0) {
                return Ok(new { code = 9999, msg = "门店不支持送货上门！" });
            }
            if (storeinfo.IsClose == 1) {
                return Ok(new { code = 9999, msg = "抱歉门店已闭店！" });
            }
            var cardlist = await _memberCardService.GetListAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            var _cardno = "";
            var _cardtype = 1;
            if (cardlist != null && cardlist.Where(c => c.IsBind == true).Count() == 2) {
                var vipcard = cardlist.Where(c => c.IsBind == true && c.CardType != "3").SingleOrDefault();
                if (vipcard != null) {
                    _cardno = vipcard.CardNO;
                }
            }
            if (string.IsNullOrEmpty(data.Paycardno)) {
                foreach (var item in cardlist) {
                    if (item.IsBind) {
                        _cardno = item.CardNO;
                        _cardtype = item.CardType.ToInt16(1);
                        break;
                    }
                }
            } else {
                var cardinfo = cardlist.Find(c => c.CardNO == data.Paycardno);
                if (cardinfo != null) {
                    _cardtype = cardinfo.CardType.ToInt16(1);
                }
                _cardno = data.Paycardno;
            }

            var goodbase = await _storeApiService.GetGoodsBase(data.storeid, data.goodsBaseId).ConfigureAwait(false);
            if (goodbase == null || goodbase.Status == 1) {
                return Ok(new { code = -22, msg = "产品已经下架" });
            }
            if (data.picktime < DateTime.Now) {
                return Ok(new { code = -25, msg = "自提时间有误" });
            }
            if (storeinfo.IsLimitStock == 0) {
                if (goodbase.StockDays > 1) {
                    if (data.picktime.DayOfYear != DateTime.Now.DayOfYear) {
                        if (data.picktime.DayOfYear < DateTime.Now.AddDays(goodbase.StockDays).DayOfYear) {
                            return Ok(new { code = -28, msg = "本款蛋糕需提前2天预定" });
                        }
                    }
                }
            }


            goodbase.Quantity = data.count;
            var storeentity = await _storeService.GetByStoreIdAsync<ICasaMielSession>(data.storeid).ConfigureAwait(false);
            if (storeentity != null) {
                goodbase.StoreName = storeentity.StoreName;
            }
             
                var dto = new IcPriceReq { Shopid = data.storeRelationId, Product = new List<ProductItemReq>(),Datasource=$"{LoginInfo.Item3}099".ToInt32(0) };
                dto.Product.Add(new ProductItemReq { Pid = $"{goodbase.GoodsRelationId}", Count = data.count });
                var iczmodel = await _icApiService.Icprice(dto).ConfigureAwait(false);
                if (iczmodel != null && iczmodel.Product.Count > 0) {
                    goodbase.Price = iczmodel.Product[0].Icprice;
                } else {
                    logger.Error($"buynowerror:{JsonConvert.SerializeObject(dto)},{JsonConvert.SerializeObject(iczmodel)}");
                    return Ok(new { code = -22, msg = "产品已经下架" });
                }

                if (DateTime.Parse(DateTime.Now.ToString("2018-05-20 20:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) < DateTime.Parse(data.picktime.ToString("2018-05-20 HH:mm:ss", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)) {
                    return Ok(new { code = -23, msg = "抱歉该自提时间不能预定" });
                }
                //if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30:00")) && data.picktime.DayOfYear == DateTime.Now.AddDays(1).DayOfYear)
                //{
                //    return Ok(new { code = -23, msg = "抱歉该时间段不能预定次日蛋糕" });
                //}
                if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)) {
                    if (data.picktime < DateTime.Parse(DateTime.Now.AddDays(1).ToString("yyyyy-MM-dd 23:00:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)) {
                        var zmodel = await _icApiService.ProductStockQuery(dto).ConfigureAwait(false);
                        if (zmodel != null && zmodel.product.Count > 0) {
                            int a = await _storeService.GetGoodsQuantityByPidAsync<ICasaMielSession>(goodbase.GoodsRelationId, DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)).ConfigureAwait(false);

                            if (zmodel.product[0].count < (data.count + a)) {
                                return Ok(new { code = -21, msg = "库存不足" });
                            }
                        } else {
                            return Ok(new { code = -21, msg = "库存不足" });
                            //logger.Error($"buynowerror:{JsonConvert.SerializeObject(dto)},{JsonConvert.SerializeObject(zmodel)}");
                            //return Ok(new { code = -22, msg = "产品已经下架" });
                        }
                        // return Ok(new { code = 0, content = goodbase, msg = "可以购买" });
                    }

                    //return Ok(new { code = 0, content = goodbase, msg = "可以购买" });

                }
                if (data.picktime.DayOfYear == DateTime.Now.DayOfYear) {
                    if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 20:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) && data.picktime.DayOfYear == DateTime.Now.DayOfYear) {
                        return Ok(new { code = -23, msg = "抱歉该时间段不能预定当天蛋糕自提" });
                    }
                    if (storeinfo.IsLimitStock == 0) {
                        var zmodle = await _icApiService.ProductStockQuery(dto).ConfigureAwait(false);
                        if (zmodle != null && zmodle.product.Count > 0) {
                            if (zmodle.product[0].count < data.count) {
                                return Ok(new { code = -21, msg = "库存不足" });
                            }
                        } else {
                            return Ok(new { code = -21, msg = "库存不足" });
                        }
                    }
                }
            
            string discountCouponName = "";
            if (data.DiscountCouponId > 0) {
                var ticketreq = new GetTicticketReq { Cardno = data.cardno, Pagesize = 200, State = 2, Pageindex = 1 };
                logger.Trace($"GeticticketReq:{JsonConvert.SerializeObject(ticketreq)}");
                var a = await _icApiService.Geticticket(ticketreq).ConfigureAwait(false);
                if (a.code == 0) {
                    var list = JsonConvert.DeserializeObject<TicketItemRoot>(a.content);
                    var ticket = list.Tickets.Where(t => t.Ticketid == data.DiscountCouponId).SingleOrDefault();
                    if (ticket != null) {
                        data.DiscountCouponMoney = ticket.Je.ToDecimal(0);
                        discountCouponName = ticket.Ticketname;
                    } else {
                        return Ok(new { code = -23, msg = "优惠券不可用" });
                    }

                    if ((data.payMethod == 3) && (_cardtype == 3)) {
                        return Ok(new { code = -41, msg = "优惠券不能与幸福卡同时使用" });
                    }
                } else {
                    return Ok(new { code = -23, msg = "优惠券不可用" });
                }
            }
            if (data.payMethod == 3) {
                if (string.IsNullOrEmpty(data.Paycardno)) {
                    return Ok(new { code = 999, msg = "卡号不能为空" });
                }
                var zcard = await _icApiService.GetCardBalance(data.Paycardno, $"{LoginInfo.Item3}099".ToInt32(0)).ConfigureAwait(false);
                if (zcard.code == 0) {
                    var cardinfo = JsonConvert.DeserializeObject<JObject>(zcard.content);
                    var balance = cardinfo["totalmoney"].ToDecimal(0);
                    if ((balance + data.DiscountCouponMoney) < (goodbase.Price * data.count)) {
                        if (_cardtype == 3)//幸福卡
                        {
                            return Ok(new { code = -40, msg = "卡内余额不足" });
                        }
                        return Ok(new { code = -39, msg = "卡内余额不足" });
                    }
                } else {
                    return Ok(zcard);
                }
            }
            var ictradeNO = "";
            var billNO = "";
            var icdto = new IcconsumeReq { Phoneno = mobile, Cardno = _cardno, Shopid = data.storeRelationId, Pickuptime = data.picktime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture) };
            icdto.Product = new List<IcconsumeReq.IcconsumeProductItem>
            {
                new IcconsumeReq.IcconsumeProductItem { Pid = $"{goodbase.GoodsRelationId}", Count = data.count }
            };
            var icentity = await _icApiService.Icconsume(icdto).ConfigureAwait(false);
            if (icentity.code == 0) {
                var jobject = JsonConvert.DeserializeObject<JObject>(icentity.content);
                ictradeNO = jobject["tradeno"].ToString();
                billNO = jobject["billno"].ToString();
            } else {
                return Ok(icentity);
            }
            var orderentity = new Order_AddSingleReq {
                Mobile = mobile,
                GoodsId = data.goodsBaseId,
                Quantity = data.count,
                Remark = data.remark,
                DiscountCouponId = data.DiscountCouponId,
                DiscountCouponMoney = data.DiscountCouponMoney,
                DiscountCouponName = discountCouponName,
                CardNO = data.cardno,
                StoreId = data.storeid,
                TakeTime = data.picktime,
                Price = goodbase.Price,
                IcTradeNO = ictradeNO,
                TakeName = data.TakeName,
                TakeMobile = data.TakeMobile,
                BillNo = billNO,
                OrderType = data.buyType == 1 ? 2 : 1,
                ConsigneeId = data.ConsigneeId
            };

            if (orderentity.OrderType == 2) {
                if (data.ConsigneeId == 0) {
                    return Ok(new { code = -30, msg = "收货地址不能空" });
                }
                var info = await _storeApiService.CheckLocation(data.storeid, data.ConsigneeId).ConfigureAwait(false);
                if (!info.IsSuccess) {
                    return Ok(new { code = -28, msg = info.ResultRemark });
                }
                //var inforesult = JsonConvert.DeserializeObject<JObject>(info);
                //if (!inforesult["ResultNo"].ToString().Equals("00000000"))
                //{
                //    return Ok(new { code = -28, msg = inforesult["ResultRemark"].ToString() });
                //}
            }
            var order = new OrderAddSingleRsp();
            try {
                logger.Trace(JsonConvert.SerializeObject(orderentity));
                var result = await _storeApiService.CreateSingleOrder(orderentity).ConfigureAwait(false);
                logger.Trace(result);
                var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
                if (dynamicdata["ResultNo"].ToString() == "00000000") {
                    order = JsonConvert.DeserializeObject<OrderAddSingleRsp>(dynamicdata["Data"].ToString());
                } else {
                    var req = new IcConsumeBackReq { Phoneno = mobile, Cardno = _cardno, Tradeno = ictradeNO };

                    var d = await _icApiService.Icconsumeback(req).ConfigureAwait(false);
                    logger.Error($"{JsonConvert.SerializeObject(req)},{JsonConvert.SerializeObject(d)}");
                    return Ok(new { code = 9999, msg = dynamicdata["ResultRemark"].ToString() });
                }
            } catch (System.Net.WebException ex) {
                var req = new IcConsumeBackReq { Phoneno = mobile, Cardno = _cardno, Tradeno = ictradeNO };

                var d = await _icApiService.Icconsumeback(req).ConfigureAwait(false);
                logger.Error($"{JsonConvert.SerializeObject(req)},{JsonConvert.SerializeObject(d)}");
                throw new CasamielDomainException("CreateOrder", ex);
            }
            var entity = await _order.GetByOrderCodeAsync<ICasaMielSession>(order.OrderCode, mobile).ConfigureAwait(false);

            var p_tradeno = $"C{DateTime.Now.ToString("yyMMddHHmmssfff", CultureInfo.CurrentCulture)}";
            var payment = new PaymentRecord { OperationMethod = 2, TradeNo = p_tradeno, Amount = entity.PayCashMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0), PayMethod = data.payMethod, BillNO = order.OrderCode, IcTradeNO = ictradeNO, State = 0, OperationState = 0, CreateTime = DateTime.Now, Mobile = mobile };

            var shopinfo = await _paymentService.GetShopIdAndShopNameByBillNOAsync<ICasaMielSession>(entity.OrderCode).ConfigureAwait(false);
            payment.ShopName = shopinfo.Item2;
            payment.ShopId = shopinfo.Item1;

            var shopno = "";
            if (payment.ShopId.HasValue) {
                var basedata = await _icApiService.BasedataQuery(new BasedataqueryReq { Datatype = 3, Datavalue = $"{payment.ShopId.Value}" }).ConfigureAwait(false);
                if (basedata.code == 0) {
                    var d = JsonConvert.DeserializeObject<JArray>(basedata.content);
                    if (d.Count > 0) {
                        shopno = d[0]["no"].ToString();
                    }
                }
            }
            if (entity.PayCashMoney == 0) {
                var pay = new IcConsumepayReq {
                    Phoneno = mobile,
                    Shopid = data.storeRelationId,
                    Tradeno = ictradeNO
                };
                pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>();
                //pay.paycontent.Add(new IcConsumepayDto.Paycontent
                //{
                //    paytype = "3",
                //    paymoney = order.OrderMoney.ToString().ToDouble(0),
                //    paytradeno = $"c{DateTime.Now.ToString("yyMMddHHmmssffff")}"
                //});
                if (data.DiscountCouponId > 0) {
                    pay.Paycontent.Add(new IcConsumepayReq.PaycontentItem {
                        Paytype = "6",
                        Paymoney = data.DiscountCouponMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                        Paytradeno = $"t{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}",
                        Payuser = $"{data.DiscountCouponId}"
                    });
                }


                var zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);
                if (zmodel.code == 0) {
                    payment.PayMethod = data.payMethod;
                    payment.PayTime = DateTime.Now;
                    payment.State = 1;
                    payment.OperationState = 1;
                    using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                        entity.OrderStatus = (int)OrderStatus.Paid;
                        entity.PayTime = DateTime.Now;
                        entity.PayMethod = payment.PayMethod;
                        await _order.OrderBaseUPdateAsync(entity, uow).ConfigureAwait(true);
                        await _order.UpdateOrderTakeStatus(entity.OrderBaseId, 0, "", uow).ConfigureAwait(true);
                        payment.State = 1;
                        payment.OperationState = 1;
                        payment.PayTime = DateTime.Now;
                        await _paymentService.AddAsync(payment, uow).ConfigureAwait(true);
                        var noticEntity = new NoticeBaseEntity() {
                            RemindTime = DateTime.Now.AddMinutes(-3),
                            CreateTime = DateTime.Now,
                            RelationId = entity.OrderBaseId,
                            StoreId = entity.StoreId,
                            NoticeType = 0
                        };
                        await _notice.AddAsync(noticEntity, uow).ConfigureAwait(true);
                    }
                    //var result = await _storeApiService.SendOrderNotice(order.OrderCode).ConfigureAwait(false);
                    return new JsonResult(new { code = 0, content = new { ordercode = entity.OrderCode, payMethod = payment.PayMethod.ToString(CultureInfo.CurrentCulture), payed = true } });
                }
                return Ok(zmodel);

            }
            switch (data.payMethod) {
                case 3://会员卡
                    var pay = new IcConsumepayReq {
                        Phoneno = mobile,
                        Cardno = data.Paycardno,
                        Shopid = data.storeRelationId,
                        Tradeno = ictradeNO,
                        Createinvoice = true
                    };
                    pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>
                    {
                        new IcConsumepayReq.PaycontentItem
                        {
                            Paytype = "3",
                            Paymoney = entity.PayCashMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                            Paytradeno = $"c{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}"
                        }
                    };
                    if (data.DiscountCouponId > 0) {
                        pay.Paycontent.Add(new IcConsumepayReq.PaycontentItem {
                            Paytype = "6",
                            Paymoney = data.DiscountCouponMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                            Paytradeno = $"t{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}",
                            Payuser = $"{data.DiscountCouponId}"
                        });
                    }


                    var zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);
                    if (zmodel.code == 0) {
                        var jobject = JsonConvert.DeserializeObject<JObject>(zmodel.content);
                        if (jobject != null && jobject["invoiceqrcode"] != null) {
                            var invoiceUrl = jobject["invoiceqrcode"].ToString();
                            await _order.UpdateOrderInvoiceUrlByOrderCodeAsync<ICasaMielSession>(payment.BillNO, invoiceUrl).ConfigureAwait(false);
                        } else {
                            logger.Error($"Invoideurl:");
                        }
                        //var jobject = JsonConvert.DeserializeObject<JObject>(zmodel.content);
                        //var tradeno = jobject["tradeno"].ToString();
                        //payment.OutTradeNo = tradeno;
                        //todo:zhifucg
                        using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                            entity.OrderStatus = (int)OrderStatus.Paid;
                            await _order.OrderBaseUPdateAsync(entity, uow).ConfigureAwait(true);
                            await _order.UpdateOrderTakeStatus(entity.OrderBaseId, 0, "", uow).ConfigureAwait(true);
                            payment.State = 1;
                            payment.Remark = $"会员卡：{data.Paycardno}";
                            payment.OperationState = 1;
                            payment.PayTime = DateTime.Now;
                            await _paymentService.AddAsync(payment, uow).ConfigureAwait(true);
                            var noticEntity = new NoticeBaseEntity() {
                                RemindTime = DateTime.Now.AddMinutes(-3),
                                CreateTime = DateTime.Now,
                                RelationId = entity.OrderBaseId,
                                StoreId = entity.StoreId,
                                NoticeType = 0
                            };
                            await _notice.AddAsync(noticEntity, uow).ConfigureAwait(true);
                        }
                        var logdata = new UserLog { Url = Request.GetShortUri(), OPInfo = $"蛋糕订单支付,卡号:[{data.Paycardno},支付金额{entity.PayCashMoney}，订单号：{entity.OrderCode}", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                        await _userLog.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
                        
                        return Ok(new { code = 0, content = new { paymentrequest = "", ordercode = order.OrderCode, payMethod = "3", payed = true } });
                    } else {
                        return Ok(zmodel);
                    }
                default:
                    var command = new CreatePaymentRequestCommand(payment, data.id, PaymentScenario.CakeStore);
                    var result = await _mediator.Send(command).ConfigureAwait(false);
                    return Ok(new { code = 0, content = result });

                    //case 1://微信支付
                    //    payment.PayMethod = 1;
                    //    payment.Remark = "app微信支付";
                    //    await _paymentService.AddAsync<ICasaMielSession>(payment);
                    //    var paymentrequst = _gateways.CreateWechatpayOrder(p_tradeno, payment.Amount);
                    //    var jsonrs = new { code = 0, content = new { paymentrequest = paymentrequst, ordercode = order.OrderCode, payMethod = "1", payed = false } };
                    //    return Ok(jsonrs);
                    ////return new JsonResult(new { code = 0, content = paymentrequst, payMethod = 1 });
                    //case 2://支付宝
                    //    payment.PayMethod = 2;
                    //    payment.Remark = "app支付宝支付";
                    //    await _paymentService.AddAsync<ICasaMielSession>(payment);
                    //    var paymentrequsta = _gateways.CreateAlipayOrder(p_tradeno, payment.Amount);
                    //    var jsonr = new { code = 0, content = new { paymentrequest = paymentrequsta, ordercode = order.OrderCode, payMethod = "2", payed = false } };
                    //    return Ok(jsonr);
                    ////return new JsonResult(new { code = 0, content = paymentrequsta, payMethod = 2, payed = false });
                    //case 4://小程序
                    //    if (data.id < 0)
                    //    {
                    //        return new JsonResult(new { code = -13, msg = "openid不存在" });
                    //    }
                    //    var wxloginentity = await _wxLogin.GetByIdAsync<ICasaMielSession>(data.id);
                    //    if (wxloginentity == null)
                    //    {
                    //        return new JsonResult(new { code = -13, msg = "openid不存在" });
                    //    }
                    //    payment.PayMethod = 4;
                    //    payment.Remark = "小程序微信支付";
                    //    await _paymentService.AddAsync<ICasaMielSession>(payment);
                    //    logger.Trace(JsonConvert.SerializeObject(wxloginentity));
                    //    var paymentrequstm = _gateways.CreateMiniWechatpayOrder(p_tradeno, payment.Amount, wxloginentity.openId, wxloginentity.appId);
                    //    var json = new { code = 0, content = new { paymentrequest = paymentrequstm, ordercode = order.OrderCode, payMethod = "4", payed = false } };
                    //    return Ok(json);
                    //return new JsonResult(new { code = 0, content = paymentrequstm, payMethod = 4, payed = false });

            }

            //return Ok(order);
        }


        /// <summary>
        /// /
        /// </summary>
        /// <returns>The buy now.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> DoncoBuyNow([FromBody]BuyNowReq data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            logger.Trace($"BuyNow:{JsonConvert.SerializeObject(data)},{mobile}");

            var storeinfo = await _storeService.GetDetail<ICasaMielSession>(data.storeid).ConfigureAwait(false);
            if (storeinfo == null) {
                return Ok(new { code = 9999, msg = "门店信息有误！" });
            }
            if (data.picktime < DateTime.Now) {
                return Ok(new { code = -25, msg = "提货时间有误" });
            }


            var goodbase = await _storeApiService.GetGoodsBase(data.storeid, data.goodsBaseId).ConfigureAwait(false);
            logger.Trace($"{JsonConvert.SerializeObject(goodbase)}");
            if (goodbase == null || goodbase.Status == 1) {
                return Ok(new { code = -22, msg = "产品已经下架" });
            }

            goodbase.StoreName = storeinfo.StoreName;

            if (storeinfo.IsLimitStock == 0) {
                if (goodbase.StockDays > 1) {
                    if (data.picktime.DayOfYear != DateTime.Now.DayOfYear) {
                        if (data.picktime.DayOfYear < DateTime.Now.AddDays(goodbase.StockDays).DayOfYear) {
                            return Ok(new { code = -28, msg = "本款蛋糕需提前2天预定" });
                        }
                    }
                }
            }
            goodbase.Quantity = data.count;
            goodbase.picktime = data.picktime;

            goodbase.storeRelationId = data.storeRelationId;
            var dto = new IcPriceReq { Shopid = data.storeRelationId, Product = new List<ProductItemReq>(),Datasource=$"{LoginInfo.Item3}099".ToInt32(0) };

            dto.Product.Add(new ProductItemReq { Pid = $"{data.relationId}", Count = data.count });
            var zmodel = await _icApiService.Icprice(dto).ConfigureAwait(false);
            if (zmodel != null && zmodel.Product.Count > 0) {
                goodbase.Price = zmodel.Product[0].Originprice;
                goodbase.CostPrice = zmodel.Product[0].Icprice;
                if (DateTime.Parse(DateTime.Now.ToString("2018-05-20 20:00:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) < DateTime.Parse(data.picktime.ToString("2018-05-20 HH:mm:ss", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)) {
                    return Ok(new { code = -23, msg = "抱歉该自提时间不能预定" });
                }
                //if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30:00")) && data.picktime.DayOfYear == DateTime.Now.AddDays(1).DayOfYear)
                //{
                //    return Ok(new { code = -23, msg = "抱歉该时间段不能预定次日蛋糕" });
                //}
                if (data.picktime.DayOfYear == DateTime.Now.DayOfYear) {
                    if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 20:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) && data.picktime.DayOfYear == DateTime.Now.DayOfYear) {
                        return Ok(new { code = -23, msg = "抱歉该时间段不能预定当天蛋糕自提" });
                    }

                }
            } else {
                logger.Error($"buynowerror:{JsonConvert.SerializeObject(dto)},{JsonConvert.SerializeObject(zmodel)}");
                return Ok(new { code = -22, msg = "产品已经下架" });
            }
            return Ok(new { code = 0, content = goodbase, msg = "可以购买" });
        }

        /// <summary>
        /// Creates the donco order.
        /// </summary>
        /// <returns>The donco order.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> CreateDoncoOrder([FromBody]CreateOrderReq data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            logger.Trace($"CreateOrder：{JsonConvert.SerializeObject(data)}");

            var storeinfo = await _storeService.GetDetail<ICasaMielSession>(data.storeid).ConfigureAwait(false);
            if (storeinfo == null) {
                return Ok(new { code = 9999, msg = "门店信息有误！" });
            }
            var cardlist = await _memberCardService.GetListAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            var _cardno = "";

            if (cardlist != null && cardlist.Where(c => c.IsBind == true).Count() == 2) {
                var vipcard = cardlist.Where(c => c.IsBind == true && c.CardType != "3").SingleOrDefault();
                if (vipcard != null) {
                    _cardno = vipcard.CardNO;
                }
            }
            if (string.IsNullOrEmpty(data.Paycardno)) {
                foreach (var item in cardlist) {
                    if (item.IsBind) {
                        _cardno = item.CardNO;
                        break;
                    }
                }
            } else {
                _cardno = data.Paycardno;
            }

            var goodbase = await _storeApiService.GetGoodsBase(data.storeid, data.goodsBaseId).ConfigureAwait(false);
            var icreq = new IcPriceReq { Product = new List<ProductItemReq>() };



            if (goodbase == null || goodbase.Status == 1) {
                return Ok(new { code = -22, msg = "产品已经下架" });
            }
            if (data.picktime.Hour < 10) {
                return Ok(new { code = -25, msg = "自提时间有误" });
            }
            if (DateTime.Parse(DateTime.Now.ToString("2018-05-20 20:00:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) < DateTime.Parse(data.picktime.ToString("2018-05-20 HH:mm:ss", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)) {
                return Ok(new { code = -23, msg = "抱歉该自提时间不能预定" });
            }
            if (data.picktime < DateTime.Now.AddHours(3)) {
                return Ok(new { code = -25, msg = "自提时间有误" });
            }
            if (data.picktime.DayOfYear == DateTime.Now.DayOfYear) {
                if (data.picktime < DateTime.Now.AddHours(3)) {
                    return Ok(new { code = -25, msg = "请提前3小时预定" });
                }
            }
            icreq.Product.Add(new ProductItemReq { Pid = $"{goodbase.GoodsRelationId}" });


            string discountCouponName = "";
            if (data.DiscountCouponId > 0) {
                var ticketreq = new GetTicticketReq { Cardno = data.cardno, Pagesize = 200, State = 2, Pageindex = 1 };
                logger.Trace($"GeticticketReq:{JsonConvert.SerializeObject(ticketreq)}");
                var a = await _icApiService.Geticticket(ticketreq).ConfigureAwait(false);
                if (a.code == 0) {
                    var list = JsonConvert.DeserializeObject<TicketItemRoot>(a.content);
                    var ticket = list.Tickets.Where(t => t.Ticketid == data.DiscountCouponId).SingleOrDefault();
                    if (ticket != null) {
                        data.DiscountCouponMoney = ticket.Je.ToDecimal(0);
                        discountCouponName = ticket.Ticketname;
                    } else {
                        return Ok(new { code = -23, msg = "优惠券不可用" });
                    }
                } else {
                    return Ok(new { code = -23, msg = "优惠券不可用" });
                }
            }
            double discount = 0;
            if (data.payMethod == 3) {
                if (string.IsNullOrEmpty(data.Paycardno)) {
                    return Ok(new { code = 999, msg = "卡号不能为空" });
                }
                var zcard = await _icApiService.GetCardBalance(data.Paycardno, $"{LoginInfo.Item3}099".ToInt32(0)).ConfigureAwait(false);
                if (zcard.code == 0) {
                    var cardinfo = JsonConvert.DeserializeObject<JObject>(zcard.content);
                    var balance = cardinfo["totalmoney"].ToDecimal(0);
                    if ((balance + data.DiscountCouponMoney) < (goodbase.Price * data.count)) {
                        return Ok(new { code = -39, msg = "卡内余额不足" });
                    }
                } else {
                    return Ok(zcard);
                }
                var product = await _icApiService.Icprice(icreq).ConfigureAwait(false);
                if (product.Product.Count > 0) {
                    discount = (goodbase.Price - product.Product[0].Icprice).ToString(CultureInfo.CurrentCulture).ToDouble(0) * data.count;
                }

            }
            var ictradeNO = "";
            var billNO = "";
            var icdto = new IcconsumeReq { Phoneno = mobile, Cardno = _cardno, Shopid = data.storeRelationId, Pickuptime = data.picktime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture) };
            icdto.Product = new List<IcconsumeReq.IcconsumeProductItem>
            {
                new IcconsumeReq.IcconsumeProductItem { Pid = $"{goodbase.GoodsRelationId}", Count = data.count }
            };
            if (data.payMethod == 3) {

            }
            var icentity = await _icApiService.Icconsume(icdto).ConfigureAwait(false);
            logger.Trace($"icconsume:{JsonConvert.SerializeObject(icdto)},{JsonConvert.SerializeObject(icentity)}");
            if (icentity.code == 0) {
                var jobject = JsonConvert.DeserializeObject<JObject>(icentity.content);
                ictradeNO = jobject["tradeno"].ToString();
                billNO = jobject["billno"].ToString();
            } else {
                return Ok(icentity);
            }
            var orderentity = new Order_AddSingleReq {
                Mobile = mobile,
                GoodsId = data.goodsBaseId,
                Quantity = data.count,
                Remark = data.remark,
                DiscountCouponId = data.DiscountCouponId,
                DiscountCouponMoney = data.DiscountCouponMoney,
                DiscountCouponName = discountCouponName,
                CardNO = data.cardno,
                StoreId = data.storeid,
                TakeTime = data.picktime,
                Price = goodbase.Price,
                IcTradeNO = ictradeNO,
                TakeName = data.TakeName,
                TakeMobile = data.TakeMobile,
                CostPrice = goodbase.CostPrice,
                BillNo = billNO,
                OrderType = data.buyType == 1 ? 2 : 1,
                ConsigneeId = data.ConsigneeId,
                Paymethod = data.payMethod
            };

            if (orderentity.OrderType == 2) {
                if (data.ConsigneeId == 0) {
                    return Ok(new { code = -30, msg = "收货地址不能空" });
                }
                var info = await _storeApiService.CheckLocation(data.storeid, data.ConsigneeId).ConfigureAwait(false);
                if (!info.IsSuccess) {
                    return Ok(new { code = -28, msg = info.ResultRemark });
                }
                //var inforesult = JsonConvert.DeserializeObject<JObject>(info);
                //if (!inforesult["ResultNo"].ToString().Equals("00000000"))
                //{
                //    return Ok(new { code = -28, msg = inforesult["ResultRemark"].ToString() });
                //}
            }
            if (data.payMethod == 3) {

            }
            var order = new OrderAddSingleRsp();
            try {
                var result = await _storeApiService.CreateSingleOrder(orderentity).ConfigureAwait(false);
                var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
                if (dynamicdata["ResultNo"].ToString().Equals("00000000")) {
                    order = JsonConvert.DeserializeObject<OrderAddSingleRsp>(dynamicdata["Data"].ToString());

                } else {
                    var req = new IcConsumeBackReq { Phoneno = mobile, Cardno = _cardno, Tradeno = ictradeNO };

                    var d = await _icApiService.Icconsumeback(req).ConfigureAwait(false);
                    logger.Error($"{JsonConvert.SerializeObject(req)},{JsonConvert.SerializeObject(d)}");
                    return Ok(new { code = 9999, msg = dynamicdata["ResultRemark"].ToString() });
                }
            } catch (System.Net.WebException ex) {
                var req = new IcConsumeBackReq { Phoneno = mobile, Cardno = _cardno, Tradeno = ictradeNO };

                var d = await _icApiService.Icconsumeback(req).ConfigureAwait(false);
                logger.Error($"{JsonConvert.SerializeObject(req)},{JsonConvert.SerializeObject(d)}");
                throw new CasamielDomainException("", ex);
            }
            var entity = await _order.GetByOrderCodeAsync<ICasaMielSession>(order.OrderCode, mobile).ConfigureAwait(false);

            var p_tradeno = $"C{DateTime.Now.ToString("yyMMddHHmmssfff", CultureInfo.CurrentCulture)}";

            var payment = new PaymentRecord { OperationMethod = (int)OperationMethod.CakeStore,
                TradeNo = p_tradeno,
                Amount = entity.PayCashMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                PayMethod = data.payMethod,
                BillNO = order.OrderCode,
                IcTradeNO = ictradeNO,
                State = 0,
                OperationState = 0,
                CreateTime = DateTime.Now, Mobile = mobile
            };
            var shopno = "";
            var shopinfo = await _paymentService.GetShopIdAndShopNameByBillNOAsync<ICasaMielSession>(order.OrderCode).ConfigureAwait(false);
            payment.ShopName = shopinfo.Item2;
            payment.ShopId = shopinfo.Item1;

            var cachekey = string.Format(CultureInfo.CurrentCulture, Constant.SHOPNO, _memcachedPrex, payment.ShopId.Value);
            shopno = await _memcachedClient.GetValueAsync<string>(cachekey).ConfigureAwait(false);
            if (string.IsNullOrEmpty(shopno)) {
                var basedata = await _icApiService.BasedataQuery(new BasedataqueryReq { Datatype = 3, Datavalue = $"{ payment.ShopId.Value}" }).ConfigureAwait(false);
                if (basedata.code == 0) {
                    var d = JsonConvert.DeserializeObject<JArray>(basedata.content);
                    if (d.Count > 0) {
                        shopno = d[0]["no"].ToString();
                        await _memcachedClient.AddAsync(cachekey, shopno, 72000).ConfigureAwait(false);
                    }
                }
            }
            payment.ShopNO = shopno;

            if (entity.PayCashMoney == 0) {
                var pay = new IcConsumepayReq {
                    Phoneno = mobile,
                    Shopid = data.storeRelationId,
                    Tradeno = ictradeNO
                };
                pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>();
                //pay.paycontent.Add(new IcConsumepayDto.Paycontent
                //{
                //    paytype = "3",
                //    paymoney = order.OrderMoney.ToString().ToDouble(0),
                //    paytradeno = $"c{DateTime.Now.ToString("yyMMddHHmmssffff")}"
                //});
                if (data.DiscountCouponId > 0) {
                    pay.Paycontent.Add(new IcConsumepayReq.PaycontentItem {
                        Paytype = "6",
                        Paymoney = data.DiscountCouponMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                        Paytradeno = $"t{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}",
                        Payuser = $"{data.DiscountCouponId}"
                    });
                }


                var zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);
                if (zmodel.code == 0) {
                    payment.PayMethod = data.payMethod;
                    payment.PayTime = DateTime.Now;
                    payment.State = 1;
                    payment.OperationState = 1;
                    using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                        entity.OrderStatus = (int)OrderStatus.Paid;
                        entity.PayTime = DateTime.Now;
                        entity.PayMethod = payment.PayMethod;
                        await _order.OrderBaseUPdateAsync(entity, uow).ConfigureAwait(true);
                        await _order.UpdateOrderTakeStatus(entity.OrderBaseId, 0, "", uow).ConfigureAwait(true);
                        payment.State = 1;
                        payment.OperationState = 1;
                        payment.PayTime = DateTime.Now;
                        await _paymentService.AddAsync(payment, uow).ConfigureAwait(true);
                        var noticEntity = new NoticeBaseEntity() {
                            RemindTime = DateTime.Now.AddMinutes(-3),
                            CreateTime = DateTime.Now,
                            RelationId = entity.OrderBaseId,
                            StoreId = entity.StoreId,
                            NoticeType = 0
                        };
                        await _notice.AddAsync(noticEntity, uow).ConfigureAwait(true);
                    }
                    //var result = await _storeApiService.SendOrderNotice(order.OrderCode).ConfigureAwait(false);
                    return new JsonResult(new { code = 0, content = new { ordercode = entity.OrderCode, payMethod = payment.PayMethod.ToString(CultureInfo.CurrentCulture), payed = true } });
                }
                return Ok(zmodel);

            }
            switch (data.payMethod) {
                case 3://会员卡
                    var pay = new IcConsumepayReq {
                        Phoneno = mobile,
                        Cardno = data.Paycardno,
                        Shopid = data.storeRelationId,
                        Tradeno = ictradeNO
                    };
                    pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>
                    {
                        new IcConsumepayReq.PaycontentItem
                        {
                            Paytype = "3",
                            Paymoney = entity.PayCashMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                            Paytradeno = $"c{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}"
                        }
                    };
                    if (data.DiscountCouponId > 0) {
                        pay.Paycontent.Add(new IcConsumepayReq.PaycontentItem {
                            Paytype = "6",
                            Paymoney = data.DiscountCouponMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                            Paytradeno = $"t{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CurrentCulture)}",
                            Payuser = $"{data.DiscountCouponId}"
                        });
                    }


                    var zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);
                    if (zmodel.code == 0) {
                        using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                            entity.OrderStatus = (int)OrderStatus.Paid;
                            await _order.OrderBaseUPdateAsync(entity, uow).ConfigureAwait(true);
                            await _order.UpdateOrderTakeStatus(entity.OrderBaseId, 0, "", uow).ConfigureAwait(true);
                            payment.State = 1;
                            payment.Remark = $"会员卡：{data.Paycardno}";
                            payment.OperationState = 1;
                            payment.PayTime = DateTime.Now;
                            await _paymentService.AddAsync(payment, uow).ConfigureAwait(true);
                            var noticEntity = new NoticeBaseEntity() {
                                RemindTime = DateTime.Now.AddMinutes(-3),
                                CreateTime = DateTime.Now,
                                RelationId = entity.OrderBaseId,
                                StoreId = entity.StoreId,
                                NoticeType = 0
                            };
                            await _notice.AddAsync(noticEntity, uow).ConfigureAwait(true);
                        }
                        var logdata = new UserLog { Url = Request.GetShortUri(), OPInfo = $"蛋糕订单支付,卡号:[{data.Paycardno},支付金额{entity.PayCashMoney}，订单号：{entity.OrderCode}", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                        await _userLog.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
                        return Ok(new { code = 0, content = new { paymentrequest = "", ordercode = order.OrderCode, payMethod = "3", payed = true } });
                    } else {
                        return Ok(zmodel);
                    }
                default:
                    var command = new CreatePaymentRequestCommand(payment, data.id, PaymentScenario.CakeStore);
                    var result = await _mediator.Send(command).ConfigureAwait(false);
                    return Ok(new { code = 0, content = result });
            }
        }
    }
}